package com.miao.im.repository;

import cn.hutool.core.collection.CollectionUtil;
import com.miao.im.domain.FriendDo;
import com.miao.im.domain.UserDo;
import com.miao.im.dto.FriendQueryDto;
import com.miao.im.repository.dao.IFriendDao;
import com.miao.im.repository.dao.IUserDao;
import com.miao.im.support.page.Page;
import com.miao.im.support.page.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/4/12 22:45
 * @Description:
 */
@Repository
public class FriendRepository implements IFriendRepository {
    @Autowired
    private IFriendDao friendDao;
    @Autowired
    private IUserDao userDao;

    @Override
    public Page<List<FriendDo>> getByUserIdPage(Long userId, Integer pageNum, Integer pageSize) {
        Page<List<FriendDo>> page = PageHelper.startPage(pageNum, pageSize);
        FriendQueryDto queryDto = new FriendQueryDto();
        queryDto.setUserId(userId);
        List<FriendDo> list = friendDao.getList(queryDto);
        if (CollectionUtil.isNotEmpty(list)){
            Map<Long, UserDo> userDoMap = this.getUserDoMap(list);
            list.forEach(f-> f.setFriend(userDoMap.get(f.getFriendId())));
        }
        page.setData(list);
        return page;
    }

    private Map<Long, UserDo> getUserDoMap(List<FriendDo> list) {
        List<Long> userIds = list.stream().map(FriendDo::getFriendId)
                .collect(Collectors.toList());
        return userDao.getInUserIds(userIds).stream()
                .collect(Collectors.toMap(UserDo::getId,
                        a -> a,
                        (k1, k2) -> k1));
    }

}
